package com.vay.de.dang.online.ui.bill;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.google.zxing.BarcodeFormat;
import com.vay.de.dang.online.VnApp;
import com.vay.de.dang.online.web.ReqResult;
import com.vay.de.dang.online.R;
import com.vay.de.dang.online.databinding.ActivityRepaymentBinding;
import com.vay.de.dang.online.entiy.MenuItemEntity;
import com.vay.de.dang.online.resp.RRepaymentAccountDto;
import com.vay.de.dang.online.resp.RRepaymentAll;
import com.vay.de.dang.online.resp.RRepaymentInfo;
import com.vay.de.dang.online.resp.RRepaymentMethodDto;
import com.vay.de.dang.online.resp.RRepaymentNumDto;
import com.vay.de.dang.online.ui.WithBack1Activity;
import com.vay.de.dang.online.ui.HomeActivity;
import com.vay.de.dang.online.util.VnUtil;
import com.vay.de.dang.online.view.DialogVoucher;
import com.vay.de.dang.online.web.BillApi;
import com.vay.de.dang.online.web.ReqCallback;

import java.util.List;

/**
 * 还款流程
 */
public class RepaymentActivity extends WithBack1Activity {

    private String applyNo;
    private ActivityRepaymentBinding binding;
    private List<RRepaymentMethodDto> ways;
    private DialogVoucher dialogVoucher;
    private String pathVoucher;
    private String repaymentType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityRepaymentBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        binding.bntClose.setOnClickListener(view -> finish());

        if (getIntent() != null) {
            applyNo = getIntent().getStringExtra("applyNo");
        }

        if (VnUtil.isEmpty(applyNo)) {
            finish();
            return;
        }

        BillApi.repaymentAllInfo(applyNo, new ReqCallback(mActivity) {

            @Override
            public void callback(ReqResult value) {
                if (value.isOk()) {
                    loadView((RRepaymentAll) value.result);
                }
            }

            @Override
            public void error(ReqResult error) {
                finish();
            }

        }.showDialog(true));
    }

    private void loadView(RRepaymentAll dto) {
        RRepaymentInfo base = dto.getInfo();
        ways = dto.getWays();

        binding.pMoneyTv.setText(VnUtil.toMoneyStr1(base.getShouldRepayAmount()));

        // 应还日期
        showItemView(binding.hkTimeLayout.getRoot(),
                getString(R.string.lc_label_5), base.getShouldReturnDate(), true);
        // 应还金额
        showItemView(binding.hkMoneyLayout.getRoot(),
                getString(R.string.lc_label_7), VnUtil.toMoneyStr1(base.getShouldRepayAmount()), true);
        // 账单状态
        showItemView(binding.billStatusLayout.getRoot(),
                getString(R.string.lc_label_8), base.isOverdue() ? VnApp.getStr(R.string.label_bill_state_5)
                        : VnApp.getStr(R.string.label_bill_state_4), true);

        // 上传凭证
        binding.bntVoucher.setOnClickListener(view -> {
            dialogVoucher = new DialogVoucher(mActivity);
            dialogVoucher.setCallback(() -> {

                if (VnUtil.isEmpty(pathVoucher)) {
                    showHint("Voucher Path is null");
                    return;
                }

                String str = binding.repayAmountTv.getText().toString();
                if (VnUtil.isEmpty(str)) {
                    showHint("Please input repayment amount");
                    return;
                }

                MenuItemEntity optionItem = dialogVoucher.getOptionItem();
                if (pathVoucher == null) {
                    showHint("Repayment voucher is null");
                    return;
                }

                BillApi.repaymentCommit(Float.parseFloat(str), applyNo, optionItem.getValue(),
                        repaymentType, pathVoucher, new ReqCallback(mActivity) {
                            @Override
                            public void callback(ReqResult value) {
                                if (value.isOk()) {
                                    HomeActivity.reloadHome();
                                    showHint(R.string.repayment_repayment_commit_ok);
                                    finish();
                                }
                            }
                        }.showDialog(true));

            });
            dialogVoucher.showChoice(ways);
        });

        // 还款金额
        repaymentType = "1";
        binding.rtAll.setVisibility(View.VISIBLE);
        binding.rtPart.setVisibility(View.VISIBLE);

        View.OnClickListener cbClick = v -> {
            int id = v.getId();
            if (id == R.id.rt_all || id == R.id.rt_exhibit) {
                binding.repayAmountTv.setEnabled(false);
                binding.rtPart.setBoxChecked(false);
                if (id == R.id.rt_all) {
                    binding.repayAmountTv.setText(String.valueOf(base.getShouldRepayAmount()));
                    repaymentType = "1";
                    binding.rtExhibit.setBoxChecked(false);
                } else {
                    binding.repayAmountTv.setText(String.valueOf(base.getExtendAmount()));
                    repaymentType = "3";
                    binding.rtAll.setBoxChecked(false);
                }
            } else if (id == R.id.rt_part) {
                binding.repayAmountTv.setEnabled(true);
                binding.repayAmountTv.requestFocus();
                repaymentType = "2";

                binding.rtAll.setBoxChecked(false);
                binding.rtExhibit.setBoxChecked(false);
            }
        };
        binding.rtAll.setViewClick(cbClick);
        binding.rtPart.setViewClick(cbClick);
        binding.rtExhibit.setViewClick(cbClick);

        // 是否可修改金额
        binding.rtAll.setBoxChecked(true);
        binding.repayAmountTv.setEnabled(false);
        binding.repayAmountTv.setText(String.valueOf(base.getShouldRepayAmount()));

        if (base.isIfCanExtend()) {
            binding.rtExhibit.setVisibility(View.VISIBLE);
            binding.rtExhibitInfo.setVisibility(View.VISIBLE);
        } else {
            binding.rtExhibit.setVisibility(View.INVISIBLE);
            binding.rtExhibitInfo.setVisibility(View.INVISIBLE);
        }

        if (ways != null) {
            binding.hintLayout.removeAllViews();
            for (int index = 0; index < ways.size(); index++) {
                RRepaymentMethodDto bean = ways.get(index);
                View iv = getLayoutInflater().inflate(R.layout.view_repayment_method, null);

                TextView tvIndex = iv.findViewById(R.id.tv_index);
                TextView tvInfo = iv.findViewById(R.id.tv_info);
                TextView tvAccount = iv.findViewById(R.id.tv_account_info);
                TextView bntCopy = iv.findViewById(R.id.bnt_copy);
                ImageView barIcon = iv.findViewById(R.id.bar_code_icon);

                tvIndex.setText(String.valueOf(index + 1));

                RRepaymentAccountDto accountDto = bean.getBankAccountResDto();
                RRepaymentNumDto numDto = bean.getRepaymentNumResDto();
                if (accountDto != null && numDto != null) {
                    String s = getString(R.string.repayment_copy_bank) + accountDto.getBankName();
                    s += "\n" + getString(R.string.repayment_copy_account) + accountDto.getBankAccountNo();
                    s += "\n" + getString(R.string.repayment_copy_hm) + accountDto.getBankAccountName();
                    if (!TextUtils.isEmpty(accountDto.getOpenAccountBank()))
                        s += "\n" + getString(R.string.repayment_copy_khh) + accountDto.getOpenAccountBank();
                    tvAccount.setText(s);

                    tvInfo.setText(R.string.repayment_copy_ok_0);
                    String numImage = numDto.getRepaymentNumImage();

                    // 1.二维码 2.条形码
                    Bitmap icon = null;
                    if (numDto.getRepaymentNumType() == 1) {
                        if (TextUtils.isEmpty(numImage)) {
                            int w = (int) getResources().getDimension(R.dimen.x200);
                            icon = VnUtil.newQRCode(BarcodeFormat.QR_CODE, numDto.getRepaymentNum(), w, w);
                        } else {
                            icon = VnUtil.decodeBitmapByBase64(numImage);
                        }
                    } else if (numDto.getRepaymentNumType() == 2) {
                        if (TextUtils.isEmpty(numImage)) {
                            int w = (int) getResources().getDimension(R.dimen.x200);
                            int h = (int) getResources().getDimension(R.dimen.x114);
                            icon = VnUtil.newQRCode(BarcodeFormat.CODABAR, numDto.getRepaymentNum(), w, h);
                        } else {
                            icon = VnUtil.decodeBitmapByBase64(numImage);
                        }
                    }

                    if (icon != null) {
                        barIcon.setVisibility(View.VISIBLE);
                        barIcon.setImageBitmap(icon);
                    }

                    final String copyInfo = s;
                    bntCopy.setOnClickListener(v -> {
                        VnUtil.copyTextClip(getString(R.string.repayment_copy_label), copyInfo);
                        showHint(R.string.repayment_copy_ok);
                    });

                    binding.hintLayout.addView(iv);
                } else if (accountDto != null) {
                    String s = getString(R.string.repayment_copy_bank) + accountDto.getBankName();
                    s += "\n" + getString(R.string.repayment_copy_account) + accountDto.getBankAccountNo();
                    s += "\n" + getString(R.string.repayment_copy_hm) + accountDto.getBankAccountName();
                    tvAccount.setText(s);
                    tvInfo.setText(R.string.repayment_copy_ok_1);
                    barIcon.setVisibility(View.GONE);

                    final String copyInfo = s;
                    bntCopy.setOnClickListener(v -> {
                        VnUtil.copyTextClip(getString(R.string.repayment_copy_label), copyInfo);
                        showHint(R.string.repayment_copy_ok);
                    });

                    binding.hintLayout.addView(iv);
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) return;

        // 凭证
        if (requestCode == 3000) {
            dialogVoucher.loadImage(pathVoucher = findString(data, "_out_path"));
        }
    }

    private void showItemView(View iv, String label, String content, boolean showLine) {
        TextView tvLabel = iv.findViewById(R.id.tv_label);
        TextView tvContent = iv.findViewById(R.id.tv_content);
        View line = iv.findViewById(R.id.line);

        tvLabel.setText(label);
        tvContent.setText(content);

        line.setVisibility(showLine ? View.VISIBLE : View.INVISIBLE);
    }
}
